package com.hbx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbx.auth.AuthCacheService;
import com.hbx.constant.CachePrefixContent;
import com.hbx.constant.CommonContent;
import com.hbx.dto.resource.PushResDto;
import com.hbx.dto.resource.SearchResDto;
import com.hbx.mapper.RankMapper;
import com.hbx.mapper.RecycleBinMapper;
import com.hbx.mapper.ResourceTypeMapper;
import com.hbx.model.Rank;
import com.hbx.model.Resource;
import com.hbx.mapper.ResourceMapper;
import com.hbx.model.ResourceType;
import com.hbx.model.User;
import com.hbx.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbx.service.UserService;
import com.hbx.utils.CacheUtils;
import com.hbx.utils.Result;
import com.hbx.utils.StringUtil;
import com.hbx.vo.PageBean;
import com.hbx.vo.PublicUserVo;
import com.hbx.vo.RankVo;
import com.hbx.vo.res.MyResVo;
import com.hbx.vo.res.ResDetailVo;
import com.hbx.vo.res.ResTypeVo;
import com.hbx.vo.res.ResourceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hbx
 * @since 2022-01-15
 */
@Service
@Slf4j
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private CacheUtils cacheUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private RankMapper rankMapper;

    @Autowired
    private RecycleBinMapper recycleBinMapper;

    @Autowired
    private ResourceTypeMapper resourceTypeMapper;

    /**
     * 发布资源
     * @param pushResDto
     * @param r
     */
    @Override
    public void pushResource(PushResDto pushResDto, Result r) {
        Resource resource = new Resource();
        BeanUtils.copyProperties(pushResDto, resource);
        User user = AuthCacheService.getUser();
        resource.setResUserid(user.getUserId());
        List<String> images = pushResDto.getResImages();
        List<String> resTagList = pushResDto.getResTagList();
        if (!CollectionUtils.isEmpty(images)){
            StringJoiner imgJoiner = new StringJoiner(",");
            StringJoiner videoJoiner = new StringJoiner(",");
            StringJoiner docJoiner = new StringJoiner(",");
            images.stream().forEach(i -> {
                String post = i.substring(i.lastIndexOf("."));
                if (Arrays.asList(CommonContent.IMG_LIST).contains(post)){
                    imgJoiner.add(i);
                }
                if (Arrays.asList(CommonContent.VIDEO_LIST).contains(post)){
                    videoJoiner.add(i);
                }
                if (Arrays.asList(CommonContent.DOC_LIST).contains(post)){
                    docJoiner.add(i);
                }
            });
            resource.setResImg(imgJoiner.toString());
            resource.setResVideoUrl(videoJoiner.toString());
            resource.setResDocUrl(docJoiner.toString());
        }

        if (!CollectionUtils.isEmpty(resTagList)){
            StringJoiner joiner = new StringJoiner(",");
            resTagList.stream().forEach(t -> joiner.add(t));
            resource.setResTags(joiner.toString());
        }

        resource.setResPushTime(new Date());
        int result = resourceMapper.insert(resource);
        if (result != 1){
            r.setData(201).setMsg("资源发布失败");
            log.error("【资源模块】:发布资源失败,{}",resource);
            return;
        }
        cacheUtils.incr(CachePrefixContent.PLAT_USER_RESOURCE + user.getUserId());
        r.setCode(200).setMsg("资源发布成功");
    }

    /**
     * 获取资源列表
     * @param search
     * @param r
     */
    @Override
    public void getResourceList(SearchResDto search, Result r) {
        String keyword = search.getKeyword();
        Integer pageNum = search.getPageNum();
        Integer pageSize = search.getPageSize();
        Integer type = search.getResType();
        PageBean pageBean = new PageBean();
        Page<Resource> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Resource> resourceQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(type) && type > 0){
            resourceQueryWrapper.eq("res_type", type);
        }
        if (StringUtils.hasLength(keyword)){
            resourceQueryWrapper.like("res_title",keyword)
                    .or().like("res_desc",keyword)
                    .or().like("res_url",keyword)
                    .or().like("res_url_desc",keyword)
                    .or().like("res_tags",keyword);
        }
        resourceQueryWrapper.eq("res_is_deleted",0)
                .orderByDesc("res_push_time");
        IPage<Resource> resourceIPage = resourceMapper.selectPage(page, resourceQueryWrapper);
        pageBean.setPageNum(resourceIPage.getCurrent());
        pageBean.setTotal(resourceIPage.getTotal());
        pageBean.setPageSize(resourceIPage.getSize());
        List<Resource> records = resourceIPage.getRecords();
        if (CollectionUtils.isEmpty(records)){
            r.setCode(200).setMsg("ok").setData(new ArrayList<>());
            return;
        }
        List<ResourceVo> list = new ArrayList<>();
        records.stream().forEach(resource -> {
            ResourceVo vo = new ResourceVo();
            BeanUtils.copyProperties(resource, vo);
            User user = userService.getById(resource.getResUserid());
            ResourceVo.UserVo userVo = new ResourceVo.UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setUserName(user.getLoginName());
            userVo.setAvatar(user.getAvator());
            List<Rank> ranks = rankMapper.selectListByUserId(resource.getResUserid());
            List<RankVo> voList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(ranks)){
                ranks.stream().forEach(rank -> {
                    RankVo rankVo = new RankVo();
                    BeanUtils.copyProperties(rank, rankVo);
                    voList.add(rankVo);
                });
            }
            userVo.setRankList(voList);
            vo.setUser(userVo);

            // b标签
            String resTags = resource.getResTags();
            if (StringUtils.hasLength(resTags)){
                vo.setResTags(Arrays.asList(resTags.split(",")));
            }
            String resImg = resource.getResImg();
            if (StringUtils.hasLength(resImg)){
                vo.setResImg(Arrays.asList(resImg.split(",")));
            }

            // 分类
            Integer resType = resource.getResType();
            if (!ObjectUtils.isEmpty(resType)){
                ResourceType resourceType = resourceTypeMapper.selectById(resType);
                if (!ObjectUtils.isEmpty(resourceType)){
                    ResTypeVo resTypeVo = new ResTypeVo();
                    BeanUtils.copyProperties(resourceType, resTypeVo);
                    vo.setType(resTypeVo);
                }
            }
            list.add(vo);
        });
        r.setCode(200).setData(list).setMsg("ok");
    }

    /**
     * 获取我的资源
     * @param pageSize
     * @param userId
     * @param r
     */
    @Override
    public void getMyResource(Integer pageSize, Integer userId, Result<MyResVo> r) {
        // 查询博客
        User user = userService.getById(userId);
        List<MyResVo> voList = new ArrayList<>();
        if (user == null){
            r.setCode(201).setMsg("用户信息不存在");
            log.error("【系统提示】:用户信息已失效");
            return;
        }
        Page<Resource> page = new Page(0, pageSize);
        QueryWrapper<Resource> wrapper = new QueryWrapper();
        wrapper.eq("res_userid",user.getUserId());
        wrapper.orderByDesc("res_push_time");
        wrapper.eq("res_is_deleted",0);

        IPage<Resource> resourceIPage = resourceMapper.selectPage(page, wrapper);
        List<Resource> resourceList = resourceIPage.getRecords();
        if (CollectionUtils.isEmpty(resourceList)){
            r.setCode(200).setData(new ArrayList<>());
            return;
        }
        resourceList.stream().forEach(resource -> {
            MyResVo myResVo = new MyResVo();
            BeanUtils.copyProperties(resource,myResVo);
            String resTags = resource.getResTags();
            if (StringUtils.hasLength(resTags)){
                myResVo.setResLableList(StringUtil.stringSpiltList(resTags, ","));
            }

            // 分类
            Integer resType = resource.getResType();
            if (!ObjectUtils.isEmpty(resType)){
                ResourceType resourceType = resourceTypeMapper.selectById(resType);
                if (!ObjectUtils.isEmpty(resourceType)){
                    ResTypeVo resTypeVo = new ResTypeVo();
                    BeanUtils.copyProperties(resourceType, resTypeVo);
                    myResVo.setType(resTypeVo);
                }
            }
            voList.add(myResVo);
        });
        r.setCode(200).setData(voList);
    }

    /**
     * 删除我的资源
     * @param resId
     * @param r
     */
    @Override
    public void removeRes(Integer resId, Result r) {
        User user = AuthCacheService.getUser();
        Resource resource = resourceMapper.selectById(resId);
        if (resource == null){
            r.setCode(201).setMsg("资源不存在,请重新加载页面");
            return;
        }
        if (!user.getUserId().equals(resource.getResUserid())){
            r.setCode(201).setMsg("非法操作,删除失败");
            return;
        }
        int result = resourceMapper.deleteById(resId);
        if (result == 1){
            r.setCode(200).setMsg("资源删除成功");
            return;
        }
        r.setCode(201).setMsg("删除失败");
    }

    /**
     * 获取资源详情
     * @param resId
     * @param r
     */
    @Override
    public void getResDetail(Integer resId, Result r) {
        Resource resource = resourceMapper.selectById(resId);
        if (resource == null){
            r.setCode(201).setMsg("资源不存在");
            return;
        }
        ResDetailVo vo = new ResDetailVo();
        BeanUtils.copyProperties(resource, vo);
        String resImg = resource.getResImg();
        String resDocUrl = resource.getResDocUrl();
        Integer resUserid = resource.getResUserid();
        String resTags = resource.getResTags();
        Integer resType = resource.getResType();
        if (StringUtils.hasLength(resImg)){
            vo.setResImg(StringUtil.stringSpiltList(resImg, ","));
        }
        if (StringUtils.hasLength(resTags)){
            vo.setResTags(StringUtil.stringSpiltList(resTags, ","));
        }
        if (!ObjectUtils.isEmpty(resType)){
            ResourceType resourceType = resourceTypeMapper.selectById(resType);
            if (resourceType != null){
                ResTypeVo resTypeVo = new ResTypeVo();
                BeanUtils.copyProperties(resourceType, resTypeVo);
                vo.setType(resTypeVo);
            }
        }

        if (StringUtils.hasLength(resDocUrl)){
            List<ResDetailVo.DocVo> list = new ArrayList<>();
            String[] items = resDocUrl.split(",");
            if (!ObjectUtils.isEmpty(items) && items.length > 0){
                for (String item : items) {
                    String fileName = item.substring(item.lastIndexOf("/") + 1);
                    ResDetailVo.DocVo docVo = new ResDetailVo.DocVo();
                    docVo.setTitle(fileName);
                    docVo.setResDocUrl(item);
                    list.add(docVo);
                }
                vo.setDocVoList(list);
            }
        }
        if (!ObjectUtils.isEmpty(resUserid)){
            User user = userService.getById(resUserid);
            if (user != null){
                PublicUserVo userVo = new PublicUserVo();
                userVo.setUserId(user.getUserId());
                userVo.setUserName(user.getLoginName());
                userVo.setAvatar(user.getAvator());
                List<Rank> ranks = rankMapper.selectListByUserId(user.getUserId());
                List<RankVo> voList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(ranks)){
                    ranks.stream().forEach(rank -> {
                        RankVo rankVo = new RankVo();
                        BeanUtils.copyProperties(rank, rankVo);
                        voList.add(rankVo);
                    });
                }
                userVo.setRankList(voList);
                vo.setUserVo(userVo);
            }
        }
        r.setCode(200).setData(vo);
    }
}
